package bootstrap

import (
	_ "SlowAdmin/pkg/logs"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"gorm.io/gorm"

	// mysql driver
	_ "github.com/go-sql-driver/mysql"

	gormMysql "gorm.io/driver/mysql"
)

var Db *gorm.DB

// init 注册mysql
func init() {
	initGorm()

	err := orm.RegisterDriver("mysql", orm.DRMySQL)
	if err != nil {
		beego.Error("mysql register driver error:", err)
	}

	dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&loc=Local",
		beego.AppConfig.String("db_username"),
		beego.AppConfig.String("db_password"),
		beego.AppConfig.String("db_host"),
		beego.AppConfig.String("db_port"),
		beego.AppConfig.String("db_database"),
	)

	err = orm.RegisterDataBase("default", beego.AppConfig.String("db_connection"), dataSource)
	if err != nil {
		logs.Error("mysql register data base error:", err)
	}
}

func initGorm() {
	var err error
	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&loc=Local&parseTime=true",
		beego.AppConfig.String("db_username"),
		beego.AppConfig.String("db_password"),
		beego.AppConfig.String("db_host"),
		beego.AppConfig.String("db_port"),
		beego.AppConfig.String("db_database"),
	)
	Db, err = gorm.Open(gormMysql.Open(dsn), &gorm.Config{})

	if err != nil {
		logs.Error(err.Error())
	}
}
